import React, { useCallback, useEffect, useRef, useState } from 'react';
import PropTypes from 'prop-types';
import { Row, Col, Input, Button, Form, DatePicker, Checkbox } from 'antd';
import { UpOutlined, DownOutlined } from '@ant-design/icons';
import classnames from 'classnames';
import moment from 'moment';
import SelectCustom from '../../input/selectCustom';
import { inputTrim } from '../../utils/utils';
import EventsBus from '../../utils/events';
import { getList } from '../util';
import './filter.less';

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};
const formItemLayoutDate = {
  labelCol: { span: 6 },
  wrapperCol: { span: 17 },
  style: {
    position: 'relative',
    left: '-12.8%',
    width: '115%',
  },
};
// 一个计数器
const num = () => {
  let mas = 0;
  return {
    clear() {
      mas = 0;
      return this;
    },
    add(item) {
      if (item.inputType === 'dataRange') {
        mas += 12;
      } else if (item.inputType === 'checkBox') {
        mas += 3;
      } else {
        mas += 6;
      }
      return mas;
    },
    getNum() {
      return mas;
    },
  };
};
// 该过滤是控制展开收起,最终获取要展示的列表数据
const getShowcolumns = (columnsList, open) => {
  const numObj = num().clear();
  const max = 18; // 计数到18即为一行
  const columns = columnsList.filter((i) => i.show);
  // 如果是展开，直接返回
  if (open) {
    return columns;
  }
  const list = []; // 待显示的列表
  for (let i = 0; i < columns.length; i += 1) {
    numObj.add(columns[i]);
    if (columns[i].show && numObj.getNum() <= max) {
      list.push(columns[i]);
    }
  }
  return list;
};
const Filter = (props) => {
  // 是否隐藏多余输入框
  const [open, setOpen] = useState(false);
  const [columns, setColumns] = useState([]);
  const {
    defaultCondition = {},
    columnsFilter,
    submitPreMiddleware,
    onReset,
    onSearch,
  } = props;
  const formRef = useRef();
  const onOpenClick = () => {
    setOpen(!open);
  };

  // 获取所有数据
  const getValues = useCallback(() => {
    let values = formRef.current.getFieldsValue();
    const valuesKey = Object.keys(values);
    for (let i = 0; i < valuesKey.length; i += 1) {
      if (values[valuesKey[i]] && values[valuesKey[i]].valueOf) {
        // 日期转化为时间戳
        values[valuesKey[i]] = values[valuesKey[i]].valueOf();
      }
    }
    // 日期输入反了，自动给他调过开
    columns.forEach((i) => {
      if (
        i.inputType === 'dataRange' &&
        i.value.length &&
        i.value.length === 2
      ) {
        // 开始调整日期
        if (
          values[i.value[0]] &&
          values[i.value[1]] &&
          Number(values[i.value[0]]) > Number(values[i.value[1]])
        ) {
          const a = values[i.value[0]];
          values[i.value[0]] = values[i.value[1]];
          values[i.value[1]] = a;
          formRef.current.setFieldsValue({
            [i.value[0]]: moment(new Date(values[i.value[0]])),
            [i.value[1]]: moment(new Date(values[i.value[1]])),
          });
        }
      }
    });
    if (submitPreMiddleware) {
      // 暴露一个外部可以处理参数的接口
      values = submitPreMiddleware(values);
    }
    return { ...defaultCondition, ...values };
  }, [formRef.current, columns, submitPreMiddleware, defaultCondition]);

  const onAdvancedSearchSubmit = useCallback(() => {
    const values = getValues();
    onSearch(values);
  }, [getValues]);

  const onAdvancedSearchReset = useCallback(() => {
    formRef.current.resetFields();
    // const values = this.getValues();
    const parms = {};
    if (onReset) {
      onReset(parms);
    }
  }, [formRef]);

  // 放开对表格对控制
  useEffect(() => {
    const userAction = {
      getValues,
    };
    const { ref } = props;
    if (ref && typeof ref !== 'function') {
      ref.current = userAction;
    }
  }, [getValues]);

  // 监听数据变化
  useEffect(() => {
    setColumns(getList(columnsFilter));
  }, [columnsFilter]);

  // 监听表单设置修改后，重新渲染
  useEffect(() => {
    const { pathname } = window.location;
    EventsBus.addListener(`${pathname}=refresh`, () => {
      setColumns(getList(columnsFilter));
    });
  }, []);

  // 渲染lable
  const labelRender = (item) => {
    if (item.labelRender) {
      // Render优先
      return item.labelRender;
    }
    const text = item.label;
    if (text && text.length > 5) {
      // 让他小一点
      return <span style={{ fontSize: '10px' }}>{text}</span>;
    }
    return text;
  };

  const list = getShowcolumns(columns, open);
  const numObj = num().clear();

  const showList = columns.filter((item) => item.show);
  return (
    <div className={classnames('filter', 'xuanyue-filter')}>
      <Form ref={formRef}>
        <div className="dashed">
          <Row gutter={24}>
            {list.map((i, index) => {
              numObj.add(i);
              let content = false;
              if (i.render) {
                content = (
                  <Col
                    // style={{ height: '48px' }}
                    span={i.inputType === 'dataRange' ? 12 : 6}
                    key={i.label}
                  >
                    {i.render(
                      FormItem,
                      i.inputType === 'dataRange'
                        ? formItemLayoutDate
                        : formItemLayout,
                      defaultCondition,
                    )}
                  </Col>
                );
              } else if (i.inputType === 'code') {
                content = (
                  <Col span={6} key={i.label}>
                    <FormItem
                      {...formItemLayout}
                      label={labelRender(i)}
                      name={i.value}
                      initialValue={defaultCondition[i.value]}
                      getValueFromEvent={inputTrim}
                    >
                      <Input placeholder="请输入" />
                    </FormItem>
                  </Col>
                );
              } else if (i.inputType === 'text') {
                content = (
                  <Col span={6} key={i.label}>
                    <FormItem
                      {...formItemLayout}
                      label={labelRender(i)}
                      name={i.value}
                      initialValue={defaultCondition[i.value]}
                      getValueFromEvent={inputTrim}
                    >
                      <Input placeholder="请输入" />
                    </FormItem>
                  </Col>
                );
              } else if (
                i.inputType &&
                i.inputType.split(',')[0] === 'select'
              ) {
                content = (
                  <Col span={6} key={i.label}>
                    <FormItem
                      {...formItemLayout}
                      label={labelRender(i)}
                      name={i.value}
                      initialValue={defaultCondition[i.value]}
                    >
                      <SelectCustom
                        optionList={i.listArr || []}
                        keyValue={i.keyValue || ['name', 'id']}
                        mode={i.inputType.split(',')[1] || ''}
                        // extraObject={{
                        //   id: currentItem.cooperativePartnerId,
                        //   name: currentItem.cooperativePartnerName,
                        // }}
                      />
                    </FormItem>
                  </Col>
                );
              } /* else if (i.inputType === 'cascaderProduct') {
                  content = (
                    <Col span={6} key={i.label}>
                      <FormItem {...formItemLayout} label={this.labelRender(i)}>
                        {getFieldDecorator(i.value, {
                          initialValue: defaultConditon[i.value],
                        })(
                          <ProductCategoryCascader
                            productList={i.listArr || props.preThis.props[props.type][i.listName]}
                          />
                        )}
                      </FormItem>
                    </Col>
                  );
                } */ else if (
                i.inputType === 'dataRange'
              ) {
                content = (
                  <Col span={12} key={i.label} style={{ overflow: 'hidden' }}>
                    <FormItem {...formItemLayoutDate} label={labelRender(i)}>
                      <Row>
                        <Col span={11}>
                          <FormItem
                            name={i.value[0]}
                            initialValue={
                              defaultCondition[i.value[0]]
                                ? moment(new Date(defaultCondition[i.value[0]]))
                                : undefined
                            }
                          >
                            <DatePicker
                              style={{ width: '100%' }}
                              format="YYYY/MM/DD"
                            />
                          </FormItem>
                        </Col>
                        <Col
                          span={2}
                          style={{
                            textAlign: 'center',
                            display: 'flex',
                            justifyContent: 'center',
                            alignItems: 'center',
                          }}
                        >
                          ~
                        </Col>
                        <Col span={11}>
                          <FormItem
                            name={i.value[1]}
                            initialValue={
                              defaultCondition[i.value[1]]
                                ? moment(new Date(defaultCondition[i.value[1]]))
                                : undefined
                            }
                          >
                            <DatePicker
                              style={{ width: '100%' }}
                              format="YYYY/MM/DD"
                            />
                          </FormItem>
                        </Col>
                      </Row>
                    </FormItem>
                  </Col>
                );
              } else if (i.inputType === 'checkBox') {
                content = (
                  <Col
                    span={3}
                    style={{
                      paddingLeft: 0,
                      paddingRight: 0,
                      position: 'relative',
                      left: '3%',
                    }}
                  >
                    <FormItem
                      valuePropName="checked"
                      name={i.value}
                      initialValue={defaultCondition[i.value]}
                    >
                      <Checkbox>{i.label}</Checkbox>
                    </FormItem>
                  </Col>
                );
              }
              if (
                numObj.getNum() === 24 ||
                numObj.getNum() === 21 ||
                (numObj.getNum() === 18 &&
                  list[index + 1] &&
                  list[index + 1].inputType === 'dataRange')
              ) {
                numObj.clear();
                return (
                  <>
                    {content}
                    <Col span={24} />
                  </>
                );
              }
              return content;
            })}
            <Col
              className="textRight"
              style={{
                float: 'right',
                marginTop: '-1px',
                marginLeft: 'auto',
                marginBottom: 12,
              }}
            >
              <Button
                style={{ marginRight: '8px' }}
                type="primary"
                onClick={onAdvancedSearchSubmit}
                htmlType="submit"
              >
                查询
              </Button>
              <Button onClick={onAdvancedSearchReset}>重置</Button>
              <a
                style={{
                  marginLeft: '8px',
                  display: showList.length <= 2 ? 'none' : '',
                }}
                onClick={onOpenClick}
              >
                {open ? '收起' : '展开'}
                {open ? (
                  <UpOutlined style={{ marginLeft: '4px' }} />
                ) : (
                  <DownOutlined style={{ marginLeft: '4px' }} />
                )}
              </a>
            </Col>
          </Row>
        </div>
      </Form>
    </div>
  );
};
Filter.propTypes = {
  columnsFilter: PropTypes.array,
  defaultCondition: PropTypes.object,
  onSearch: PropTypes.func,
  onReset: PropTypes.func,
  submitPreMiddleware: PropTypes.func, // 暴露一个外部可以处理参数的接口
  iconStyle: PropTypes.object,
};
export default Filter;
